package com.whfc.emp.websocket;

import com.whfc.common.third.helmet.HelmetProperties;
import com.whfc.emp.helmet.ZbznVideoParse;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.net.URI;
import java.util.Timer;
import java.util.TimerTask;

@Slf4j
@Component
public class SocketConfig {

//    public final String url = "wss://111.120.11.161:10006/wss";
    public final String url = "ws://111.120.11.161:10000/wss";

    @Autowired
    private ZbznVideoParse zbznVideoParse;

    @Autowired
    private HelmetProperties helmetProperties;

    @Bean(name = "zbznWebSocket")
    public WebSocketClient webServiceClient() {
        try {
            ZbznWebSocketClient mWebSocketClient = new ZbznWebSocketClient(new URI(url));
            mWebSocketClient.setZbznVideoParse(zbznVideoParse);
            mWebSocketClient.setHelmetProperties(helmetProperties);
            mWebSocketClient.connect();

            //如果断线，则重连并重新发送验证信息
            Timer t = new Timer();
            t.scheduleAtFixedRate(new TimerTask() {
                @Override
                public void run() {
                    if (mWebSocketClient.isClosed()) {
                        mWebSocketClient.reconnect();
                        // 在WebSocket连接建立后调用login方法
                        Timer loginTimer = new Timer();
                        loginTimer.schedule(new TimerTask() {
                            @Override
                            public void run() {
                                if (mWebSocketClient.WEBSTATUS) {
                                    zbznVideoParse.login();
                                    loginTimer.cancel(); // 取消定时器，只执行一次
                                }
                            }
                        }, 0, 1000); // 延迟0毫秒，每隔1秒检查一次连接状态
                    }

                }
            }, 2000, 10000);//10秒执行一次 然后休息2秒
            return mWebSocketClient;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
